<?php
namespace app\api\controller;

class AdminRoles extends Permission
{
    public function getList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 15;
        $map = [
            'delete_time' => 0
        ];
        
        $total = db('AdminRoles')->where($map)->count();
        $list = db('AdminRoles')->where($map)->select();

        
        $data = array(
            'count' => $total,
            'list' => $list     
        );
        $this->resSuc($data);
    }
    
    public function del()
    {
        $map['id'] = $this->input_data['id'];
        $data = [
            'delete_time' => time(),
            'delete_user' => $this->user['realname'],
            'delete_user_id' => $this->user['id']
        ];
        db('AdminRoles')->where($map)->update($data);
        $this->resSuc('ok');
    }

    public function update()
    {
        $data['title'] = $this->input_data['title'];
        
        if($this->input_data['id'] > 0)
        {
            $data['id'] = $this->input_data['id'];
            db('AdminRoles')->update($data);
        }
        else
        {
            $id = db('AdminRoles')->insertGetId($data);
        }

        $this->resSuc('success');
    }

    public function getRouter()
    {
        $router = db('AdminRouter')->select();

        $map = [
            'id' => $this->input_data['id']
        ];
        $menus = db('AdminRoles')->where($map)->find();
        $ids = explode(',', $menus['router']);

        foreach ($router as $k => $v) {
            $router[$k]['checked'] = false;
            if( in_array($v['menuId'], $ids) ) $router[$k]['checked'] = true;
        }

        $this->resSuc($router);

    }

    public function updateRouter()
    {
        $map = [
            'id' => $this->input_data['roles_id']
        ];
        $ids = explode("]", $this->input_data['ids']);
        $ids = explode('[',$ids[0]);
        $ids = $ids[1];
        // $ids = json_decode($this->input_data['ids'],true);

        $data = [
            'router' => $ids
        ];
        db('AdminRoles')->where($map)->update($data);

        # 更新用户组里面所有用户的权限
        $map = [
            'roles_id' => $this->input_data['roles_id']
        ];
        db('AdminRules')->where($map)->delete();

        $map = [
            'roles' => $this->input_data['roles_id']
        ];
        $admin = db('Admin')->where($map)->select();
        $rules = json_decode($this->input_data['ids'],true);
        foreach ($admin as $v) {
            foreach($rules as $r)
            {
                $data = [
                    'admin_id' => $v['id'],
                    'router_id' => $r,
                    'roles_id' => $this->input_data['roles_id'],
                ];
                db('AdminRules')->insert($data);
            }
        }

        $this->resSuc('ok');
    }

    
}
